package com.example.myapplication.mention

import android.content.Context
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText

/**
 * Create by Tanzhenxing on 2025/9/1.
 * Description:
 */
class MentionEditText : AppCompatEditText {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private var lastTextLength = 0

    init {
        addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                lastTextLength = s?.length ?: 0
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 不需要处理
            }

            override fun afterTextChanged(s: Editable?) {
                if (s == null) return

                // 检测是否是删除操作（长度减少）
                if (s.length < lastTextLength) {
                    handleBackspace()
                }
            }
        })
    }

    private fun handleBackspace() {
        val selectionStart = selectionStart
        val selectionEnd = selectionEnd

        if (selectionStart == selectionEnd) { // 普通删除（非选中状态）
            val text = text as? SpannableStringBuilder ?: return
            val mentionSpans = text.getSpans(selectionStart - 1, selectionStart, MentionSpan::class.java)

            if (mentionSpans.isNotEmpty()) {
                val span = mentionSpans[0]
                val spanStart = text.getSpanStart(span)
                val spanEnd = text.getSpanEnd(span)

                if (selectionStart == spanEnd) {
                    // 删除整个 @提及
                    text.delete(spanStart, spanEnd)
                    return
                }
            }
        }
    }
}